package com.itheima.activiti.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.activiti.auth.JwtContextUtils;
import com.itheima.activiti.dto.system.MenuDTO;
import com.itheima.activiti.service.system.MenuService;
import com.itheima.authority.api.v1.MenuApi;
import com.itheima.authority.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuApi menuApi;

    @Override
    public List<MenuDTO> router() {
        Long userId = JwtContextUtils.getUser().getId();
        R<List<com.itheima.authority.api.v1.dto.VueRouter>> menuResult = menuApi.myRouter(null, userId);

        List<MenuDTO> menuDTOList = new ArrayList<>();
        if (menuResult.getIsSuccess()) {
            vueRouterCopy(menuResult.getData(), menuDTOList);
        }
        return menuDTOList;
    }

    private void vueRouterCopy(List<com.itheima.authority.api.v1.dto.VueRouter> vueRouterList, List<MenuDTO> menuDTODTOList) {
        for (com.itheima.authority.api.v1.dto.VueRouter datum : vueRouterList) {
            MenuDTO menuDTO = new MenuDTO();
            BeanUtil.copyProperties(datum, menuDTO);
            if (!CollectionUtils.isEmpty(datum.getChildren())) {
                List<MenuDTO> menuDTODTOChildrenList = new ArrayList<>();
                vueRouterCopy(datum.getChildren(), menuDTODTOChildrenList);
                menuDTO.setChildren(menuDTODTOChildrenList);
            }
            menuDTODTOList.add(menuDTO);
        }
    }

}
